const {
    add,
    del,
    edit,
    search,
    searchBy,
} = require('../js/mysql.js')
const router = require('koa-router')()
const jwtAuth = require('../jwtAuth')
router.use(jwtAuth)

router.prefix('/recycle')

// ===========================用户=============================
// 分页/搜索列表展示
router.get('/user', async (ctx, next) => {
    const { page = 1, limit = 3, search = "" } = ctx.request.query;
    let sql1 = `state=0 and (account LIKE '%${search}%' or name LIKE '%${search}%')`;
    let sql2 = `state=0 and (account LIKE '%${search}%' or name LIKE '%${search}%') order by id DESC LIMIT ${(page - 1) * limit},${limit}`;
    let total = await searchBy(sql1);
    let data = await searchBy(sql2);
    ctx.body = {
        code: 200,
        msg: "操作成功",
        data,
        total: total.length
    }
})
// 还原
router.put('/reduc', async (ctx, next) => {
    const IDlist = ctx.request.body;
    for (let i in IDlist) {
        await edit([1], `state=1 where id=${IDlist[i]}`);
    };
    ctx.body = {
        code: 200,
        msg: "操作成功",
    }
})
// 删除（真）
router.delete('/userdelf', async (ctx, next) => {
    const IDlist = ctx.request.body;
    for (let i in IDlist) {
        await del(`id=${IDlist[i]}`)
    };
    ctx.body = {
        code: 200,
        msg: '操作成功'
    }
})

// ===========================培训=============================
// 分页/搜索列表展示
router.get('/train', async (ctx, next) => {
    const { page = 1, limit = 3, search = "" } = ctx.request.query;
    let sql1 = `(user_state=0 or train_state=6) and (train_name LIKE '%${search}%' or train_admin LIKE '%${search}%')`;
    let sql2 = `(user_state=0 or train_state=6) and (train_name LIKE '%${search}%' or train_admin LIKE '%${search}%') order by id DESC LIMIT ${(page - 1) * limit},${limit}`;
    let total = await searchBy(sql1, 'train');
    let data = await searchBy(sql2, 'train');
    ctx.body = {
        code: 200,
        msg: "操作成功",
        data,
        total: total.length
    }
})
// 根据管理者查询用户是否存在
router.get('/inquire',async(ctx,next) => {
    const {account} =ctx.request.query;
    console.log(account);
    let data = await searchBy(`account='${account}' and state=1`);
    ctx.body = {
        code: 200,
        msg: "操作成功",
        data: data.length
    }
})
// 还原
router.put('/reductrain/:id', async (ctx, next) => {
    const {id} = ctx.params;
    await edit([0], `train_state=0 where id=${id}`,'train');
    ctx.body = {
        code: 200,
        msg: "操作成功",
    }
})
// 删除（真）
router.delete('/traindelf', async (ctx, next) => {
    const IDlist = ctx.request.body;
    for (let i in IDlist) {
        await del(`id=${IDlist[i]}`, 'train')
    };
    ctx.body = {
        code: 200,
        msg: '操作成功'
    }
})

module.exports = router